package View;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.*;
import javax.swing.*;
import javax.media.*;

import Model.ListSlideModel;

import kdiapo.Main;
import kdiapo.Resizable;
import kdiapo.SlideShow;
import kdiapo.CreationFrame;

public class VideoView extends ElementView {
	
	private String path; 
	
	private Resizable resizer;
	
	private JPanel mainPanel;
	private Player player = null;
	private boolean paused = false;
	private Time resume;
	private GridBagLayout gbl;
	private GridBagConstraints gbc;
	
	
	public VideoView(CreationFrame frame, int num, File f){		
		super(frame,num);
		
		mainPanel = this; 
		
		this.path = f.getAbsolutePath();
		
		gbl = new GridBagLayout();
        gbc = new GridBagConstraints();

        this.setBounds(100, 100,300,300);
        
        this.createPlayer(f);
        this.resizer = new Resizable(this);
        this.resizer.setBounds(100,100, 300,300);
        
        mainPanel.setLayout(gbl);
        
        ListSlideModel md = getMainFrame().getModel();
	    md.setPosition(num, 100,  100, 300, 300);
        
        // waiting for the player to be ready
        while (player.getMediaTime().getSeconds() < 0.1){
     	   
        }
        if (player.getMediaTime() != null)
     	   System.out.println("media time : "+player.getMediaTime().getSeconds());
        System.out.println("pause");
        this.pause();
        
        addListeners();
	}
	
	public VideoView(CreationFrame frame,int num,File f,int X,int Y,int width,int height){
		super(frame,num);
		
		mainPanel = this; 
		
		this.path = f.getAbsolutePath();
		
		gbl = new GridBagLayout();
        gbc = new GridBagConstraints();

        this.setBounds(X,Y,width,height);
        
        this.createPlayer(f);
        this.resizer = new Resizable(this);
        this.resizer.setBounds(X,Y,width,height);
        
        mainPanel.setLayout(gbl);
        
        // waiting for the player to be ready
        while (player.getMediaTime().getSeconds() < 0.1){
     	   
        }
        if (player.getMediaTime() != null)
     	   System.out.println("media time : "+player.getMediaTime().getSeconds());
        System.out.println("pause");
        this.pause();
        
        addListeners();
		
	}
	
	public VideoView(SlideShow frame,int num,File f,int X,int Y,int width,int height){
		super(num);
		
		mainPanel = this; 
		
		this.path = f.getAbsolutePath();
		
		gbl = new GridBagLayout();
        gbc = new GridBagConstraints();

        this.setBounds(X,Y,width,height);
        
        this.createPlayer(f);
        this.resizer = new Resizable(this);
        this.resizer.setBounds(X,Y,width,height);
        
        mainPanel.setLayout(gbl);
        
        // waiting for the player to be ready
        while (player.getMediaTime().getSeconds() < 0.1){
     	   
        }
        if (player.getMediaTime() != null)
     	   System.out.println("media time : "+player.getMediaTime().getSeconds());
        System.out.println("pause");
        this.pause();
        
        //addListeners();
		
	}
	
	public Resizable getResizer(){
		return this.resizer;
	}
	public void createPlayer(File file)
	   {
	      if (file == null)
	         return;

	      removeCurrentPlayer();
	      
	      mainPanel.removeAll();

	      try {
	         // create a new player and add listener
	         player = Manager.createPlayer( file.toURI().toURL() );
	         player.addControllerListener(new EventHandler());
	         // start player
	         player.start();  
	         
	      }
	      catch ( Exception e ){
	         JOptionPane.showMessageDialog( this,"Invalid file or location", 
	        		 "Error loading file", JOptionPane.ERROR_MESSAGE );
	      }
	      
	      
	   }
	
	public void addListeners(){
		this.resizer.addKeyListener(new KeyListener() {
			public void keyTyped(KeyEvent e) {}			
			public void keyReleased(KeyEvent e) {
				
				if(e.getKeyCode() == KeyEvent.VK_DELETE){

					System.out.println("Num Element to delete:"+getNumElement());
					//Suppression de l'�l�ment de la vue
					int num = getNumElement();
					
					getMainFrame().removeElement(num);
					
					
					//Mise � jour du mod�le
					getMainFrame().getModel().removeElement(num);
				}
			}
			
			
			public void keyPressed(KeyEvent e) {}
		});
		this.resizer.addComponentListener(new ComponentListener() {
			public void componentShown(ComponentEvent e) {}
			public void componentResized(ComponentEvent e) {
				//System.out.println("largeur="+imageIcon.getIconWidth()+"\tlongueur="+imageIcon.getIconHeight());
				
				getMainFrame().getModel().setPosition(getNumElement(), 
						getMainFrame().getCurrentSlide().getComponent(getNumElement()).getX(),
						getMainFrame().getCurrentSlide().getComponent(getNumElement()).getY(), 
						resizer.getWidth(),
						resizer.getHeight());
		
			}
			public void componentMoved(ComponentEvent e) {				
				System.out.println("X="+getMainFrame().getCurrentSlide().getComponent(getNumElement()).getX()
						+"\tY="+getMainFrame().getCurrentSlide().getComponent(getNumElement()).getX());
				getMainFrame().getModel().setPosition(getNumElement(), 
						getMainFrame().getCurrentSlide().getComponent(getNumElement()).getX(),
						getMainFrame().getCurrentSlide().getComponent(getNumElement()).getY(), 
						resizer.getWidth(),
						resizer.getHeight());
			}
			public void componentHidden(ComponentEvent e) {}
			
		});
		this.resizer.addMouseListener(new MouseListener() {
			public void mouseReleased(MouseEvent e) {
				if (e.isPopupTrigger())
		            doPop(e);	
			}
			public void mousePressed(MouseEvent e) {
				if (e.isPopupTrigger())
		            doPop(e);
			}
			public void mouseExited(MouseEvent e) {}
			public void mouseEntered(MouseEvent e) {}
			
			public void mouseClicked(MouseEvent e) {}
			public void doPop(MouseEvent e){
				JPopupMenu popMenu = new JPopupMenu();
				JMenuItem anItem =  new JMenuItem("Remove this element");
				anItem.setIcon(new ImageIcon(Main.class.getResource("/remove_icon.png")));
				anItem.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent e) {
						//Suppression de l'�l�ment de la vue
						removeElement(getNumElement());
					}
				});
				
				popMenu.add(anItem);
				popMenu.show(e.getComponent(), e.getX(), e.getY());
			}
		});
	}
	
	public void removeElement(int num){
		getMainFrame().removeElement(num);
		//Mise � jour du mod�le
		getMainFrame().getModel().removeElement(num);
	}
	
	private void removeCurrentPlayer()
	   {
	      if (player == null)
	         return;

	      player.close();

	      Component visual = player.getVisualComponent();
	      Component control = player.getControlPanelComponent();

	      	     
	      if (visual != null) 
	    	  mainPanel.remove(visual);

	      if (control != null)  
	    	  mainPanel.remove(control);
	   }
	
	
	// inner class to handler events from media player
	private class EventHandler implements ControllerListener {
	      public void controllerUpdate( ControllerEvent e ) {
	         if (e instanceof RealizeCompleteEvent) {
	         
	            // load Visual and Control components if they exist
	            Component visualComponent = player.getVisualComponent();
	            
	            // if the visual component exists, add it 
	            gbc.gridx = 0;
	            gbc.gridy = 0;
	            gbc.weightx = 1;
	            gbc.weighty = 0.95;
	            gbc.fill = GridBagConstraints.BOTH;
	            if (visualComponent != null)
	               mainPanel.add(visualComponent, gbc);

	            Component controlsComponent = player.getControlPanelComponent();
	            
	            // if the control panel component exists, add it
	            gbc.gridx = 0;
	            gbc.gridy = GridBagConstraints.RELATIVE;
	            gbc.weightx = 1;
	            gbc.weighty = 0.06;
	            gbc.gridheight = 1;
	            gbc.fill = GridBagConstraints.BOTH;
	            if ( controlsComponent != null )
	               mainPanel.add(controlsComponent, gbc);

	            //mainPanel.doLayout();
	         }
	      }
	   }
	
	public void pause(){
		   if(paused){
			   player.setMediaTime(resume);
			   player.start();
			   paused = false;
	   
		   }
		   else {   
			   resume = player.getMediaTime();
			   player.stop();
			   paused = true;
	   	   }
	   }
	
	public Player getPlayer(){
		return player;
	}
}


/*

private void closeCurrentPlayer() {
        if (player != null) {
            player.stop();
            player.close();
        }
    }

*/
